//const imagePrefix = "http://read.html5.qq.com/image?src=forum&q=5&r=0&imgflag=7&imageUrl=";
const imagePrefix = "";

function formatTime(number,format) {
    if(number===null||!number){
        return null;
    }
    const formateArr  = ['Y','M','D','h','m','s'];
    let returnArr   = [];

    let date = new Date(number);
    returnArr.push(date.getFullYear());
    returnArr.push(formatNumber(date.getMonth() + 1));
    returnArr.push(formatNumber(date.getDate()));

    returnArr.push(formatNumber(date.getHours()));
    returnArr.push(formatNumber(date.getMinutes()));
    returnArr.push(formatNumber(date.getSeconds()));

    for (let  i in returnArr){
        format = format.replace(formateArr[i], returnArr[i]);
    }
    return format;
}

function genStartEndTime(start, end) {
    start = formatTime(start,'Y.M.D');
    end = formatTime(end,'Y.M.D');
    if(!start||!end){
        return {start:'', end:''}
    }
    if(start.substring(0,4)===end.substring(0,4)){
        return {start, end:end.split('.')[1]+'.'+end.split('.')[2]}
    }else{
        return {start, end}
    }
}

/**
 * 格式化数字为两位数
 * @param n 目标数字
 * @returns {*}
 */
function formatNumber(n) {
    n = n.toString();
    //return n[1] ? n : '0' + n;
    return n;
}

/**
 * 把拍品结束时间转换成倒计时样式
 * @param endTime 结束时间
 * @param errorTime 服务器当前时间与手机当前时间的误差
 * @returns {*} 倒计时样式
 */
function endTimeToCountDownStr(endTime,errorTime) {
    if (!endTime) {
        return "获取中，请刷新";
    } else {
        var endTimeDate = new Date(endTime),
            endYear = endTimeDate.getFullYear(),
            endMonths = endTimeDate.getMonth() + 1,
            endDays = endTimeDate.getDate(),
            endHours = endTimeDate.getHours(),
            endMinutes = endTimeDate.getMinutes(),
            endSeconds = endTimeDate.getSeconds(),

            nowDate = new Date(new Date().getTime()-errorTime),
            nowYear = nowDate.getFullYear(),
            nowMonths = nowDate.getMonth() + 1,
            nowDays = nowDate.getDate(),
            nowHours = nowDate.getHours(),
            nowMinutes = nowDate.getMinutes(),
            nowSeconds = nowDate.getSeconds();
        //计算秒
        if (endSeconds - nowSeconds < 0) {
            endMinutes--;
            endSeconds += 60;
        }
        var leftSeconds = endSeconds - nowSeconds;
        //计算分钟
        if (endMinutes - nowMinutes < 0) {
            endHours--;
            endMinutes += 60;
        }
        var leftMinutes = endMinutes - nowMinutes;
        //计算小时
        if (endHours - nowHours < 0) {
            endDays--;
            endHours += 24;
        }
        var leftHours = endHours - nowHours;
        //计算天
        if (endDays - nowDays < 0) {
            endMonths--;
            if (endMonths == 4 || endMonths == 6 || endMonths == 9 || endMonths == 11) {
                endDays += 30;
            } else if (endMonths == 2) {
                if (isLeapYear(endYear)) {
                    endDays += 29;
                } else {
                    endDays += 28;
                }
            } else {
                endDays += 31;
            }
        }
        var leftDays = endDays - nowDays;
        //计算月
        if (endMonths - nowMonths < 0) {
            endYear--;
            endMonths += 12;
        }
        var leftMonths = endMonths - nowMonths;
        //计算年
        var leftYears = endYear - nowYear;

        return (leftYears > 0 ? leftYears + "年 " : "") +
            (leftMonths > 0 ? leftMonths + "月 " : "") +
            (leftDays > 0 ? leftDays + "天 " : "") +
            formatNumber(leftHours) + ":" +
            formatNumber(leftMinutes) + ":" +
            formatNumber(leftSeconds);
    }
}

/**
 * 判断是否是闰年
 * @param year number形式的年份
 * @returns {boolean}
 */
function isLeapYear(year) {
    return (year % 4 == 0) && (year % 100 != 0 || year % 400 == 0);
}

/**
 * 把毫秒值按要求转换成特定的日期字符串
 * @param str 时间毫秒值
 * @param ty 拍品状态
 * @returns {*} 格式化后的时间字符串
 */
function timeToSpecialStr(str, ty) {
    var t = new Date(parseInt(str));
    var YYYY = t.getFullYear(),
        M = t.getMonth() + 1,
        D = t.getDate(),
        h = t.getHours(),
        m = t.getMinutes(),
        s = t.getSeconds(),
        z = t.getDay();
    var MM = formatNumber(M),
        DD = formatNumber(D),
        hh = formatNumber(h),
        mm = formatNumber(m),
        ss = formatNumber(s);

    if (!ty) {
        ty = Math.abs(new Date().getFullYear() - YYYY) >= 1 ? 2 : 1;
    }

    switch (ty) {
        case 1:
            return MM + '/' + DD + ' ' + hh + ':' + mm;
            break;
        case 2:
            return YYYY + '/' + MM + '/' + DD;
            break;
        case 4:
            var weekStrs = ["周日", "周一", "周二", "周三", "周四", "周五", "周六"];
            return MM + '-' + DD + ' ' + weekStrs[z];
            break;
        case 5:
            var today = new Date().toDateString();
            var now = new Date(parseInt(str)).toDateString();
            if (today == now) {
                return '今天 ' + hh + ':' + mm;
            } else if (today - t < 60 * 60 * 24 * 1000 * 2) {
                return '昨天';
            } else {
                return MM + '-' + DD;
            }
            break;
        case 10:
           /* YYYY = YYYY - 1970;
            if (YYYY < 10) YYYY = '000' + YYYY;
            else if (YYYY < 100) YYYY = '00' + YYYY;
            else if (YYYY < 1000) YYYY = '0' + YYYY;*/
            return YYYY + '-' + MM + '-' + DD + ' ' + hh + ':' + mm + ':' + ss;
            break;
        case 11:
            return YYYY + '-' + MM + '-' + DD + ' ' + hh + ':' + mm;
            break;
        default:
            break;
    }
}





function toast(msg,state='success') {
    wx.showToast({
        title: msg,
        icon: state,
        duration: 2000,
        mask:true
    });
}


function previewImage(index, urls) {
    var urlContainer=[];
    for (var i=0;i<urls.length;i++){
        urlContainer.push(urls[i].bigUrl);
    }
    wx.previewImage({
        current: urlContainer[index],
        urls: urlContainer
    });
}

function saveToLocal(key,value){
    wx.setStorage({key,data:value})
}

function getFromLocal(key){
    let value;
    try {
        value = wx.getStorageSync(key);
    } catch (e) {
        value='';
    }
    return value;
}

function deleteFromLocal(key){
    wx.removeStorage({
        key
    });
}

// 防抖动函数
function debounce(func, wait, immediate) {
    var timeout;
    return function() {
        var context = this, args = arguments;
        var later = function() {
            timeout = null;
            if (!immediate) func.apply(context, args);
        };
        var callNow = immediate && !timeout;
        clearTimeout(timeout);
        timeout = setTimeout(later, wait);
        if (callNow) func.apply(context, args);
    };
}

function replaceText(txt){
    txt = txt.replace(/&#34;/g,'"');
    txt = txt.replace(/&#35;/g,'#');
    txt = txt.replace(/&#36;/g,'$');
    txt = txt.replace(/&#38;/g,'&');
    txt = txt.replace(/&#39;/g,"'");
    txt = txt.replace(/&#40;/g,'(');
    txt = txt.replace(/&#41;/g,')');
    txt = txt.replace(/&#59;/g,';');
    txt = txt.replace(/&#60;/g,'<');
    txt = txt.replace(/&#62;/g,'>');
    txt = txt.replace(/&#x27;/g,'\'');
    return txt;
}


module.exports = {
    timeUtil:{
        formatDateNumber:formatNumber,
        genStartEndTime,formatTime,
        timeToSpecialStr: timeToSpecialStr,
        endTimeToCountDownStr: endTimeToCountDownStr,
        isLeapYear:isLeapYear,
    },
    storage:{
        saveToLocal,getFromLocal,deleteFromLocal
    },
    toast,
    previewImage,
    debounce,
    imagePrefix,
    recoverHtml:replaceText
};
